﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMdiSubWindow>
#include <QLabel>
#include <QMessageBox>
#include <QProcess>
#include <QInputDialog>
#include <QDebug>
#include <QPluginLoader>
#include <QDesktopServices>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    actionSeparator = new QAction(this); // 创建间隔器动作
    actionSeparator->setSeparator(true); // 在其中设置间隔器
    initWindow();
    //设置窗口更新
    updateMenus();
    updateWindowsTimer.start(UPDATESPEED);
    connect(&updateWindowsTimer, SIGNAL(timeout()), this, SLOT(updateMenus()));

    //根据设置初始化
    setting_config = new QSettings(INICONFIG,QSettings::IniFormat,0);
    setting_config->setIniCodec("GB2312");
    readSettings();

    //检查发送队列是否有数据需要发送
    connect(&sendtimer,SIGNAL(timeout()),
            this,SLOT(checkQueueData_slot()));
    //串口操作
    connect(&userUart,SIGNAL(sig_readfinish(int)),
            this,SLOT(uartgetdata_slot(int)));
    connect(this,SIGNAL(sig_readytosent()),
            this,SLOT(uartsentdata_slot()));
    connect(this,SIGNAL(sig_transfers_stop(int)),
            this,SLOT(transfers_stop_slot(int)));
    fileTranferFlag = false;

    //打开拖入文件
    connect(ui->mdiArea,SIGNAL(sig_dropFile(QString)),this,SLOT(FileOpen_slot(QString)));
    //最近打开列表
    connect(this,SIGNAL(sig_savelastfile(QStringList)),ui->menu_recent,SLOT(reloadList(QStringList)));
}

MainWindow::~MainWindow()
{
    delete ui;
    delete setting_config;
}

// 初始化窗口
void MainWindow::initWindow()
{
    //功能子窗口
    widget_f = new widget_find;
    connect(widget_f, SIGNAL(sig_findString(QString,QTextDocument::FindFlags)),
            this, SLOT(showFindText_SLOT(QString,QTextDocument::FindFlags)));
    widget_r = new widget_replace;
    connect(widget_r, SIGNAL(sig_findString(QString,QString,QTextDocument::FindFlags, int)),
            this, SLOT(showReplaceText_SLOT(QString,QString,QTextDocument::FindFlags, int)));
    widget_ab = new widget_about;

    widget_s = new widget_setting;
    //重载设置功能
    connect(widget_s,SIGNAL(sig_setting_changed()), this,SLOT(reload_setting_slot()));
#if OEM
    setWindowTitle(tr(SOFEWARENAMEOEM));
    QIcon icon;
    icon.addFile(QStringLiteral(":/myImage/images/Simulation.ico"), QSize(), QIcon::Normal, QIcon::Off);
    setWindowIcon(icon);
#else
    setWindowTitle(tr(SOFEWARENAME));
    QIcon icon;
    icon.addFile(QStringLiteral(":/myImage/images/icon.jpg"), QSize(), QIcon::Normal, QIcon::Off);
    setWindowIcon(icon);
#endif
    // 在工具栏上单击鼠标右键时，可以关闭工具栏
    ui->mainToolBar->setWindowTitle(tr("工具栏"));

    // 当多文档区域的内容超出可视区域后，出现滚动条
    ui->mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    ui->mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

#if OEM
#else
    //右下标志
    QLabel *label = new QLabel(this);
    label->setFrameStyle(QFrame::Box | QFrame::Sunken);
    label->setText(
          tr("<a href=\"http://www.brjcnc.com/\">深圳市博锐捷数控技术有限公司</a>"));
    label->setTextFormat(Qt::RichText); // 标签文本为富文本
    label->setOpenExternalLinks(true);  // 可以打开外部链接
    ui->statusBar->addPermanentWidget(label);
#endif
    downloadPb = new QProgressBar();
    downloadPb->setValue(0);
    downloadPb->setVisible(false);
    cancelButton = new QPushButton();
    cancelButton->setText(tr("取消"));
    cancelButton->setVisible(false);
    ui->statusBar->addWidget(downloadPb);
    ui->statusBar->addWidget(cancelButton);
    connect(this, SIGNAL(sig_processChange(int)),
            downloadPb, SLOT(setValue(int)));
    connect(cancelButton, SIGNAL(clicked()),
            this, SLOT(transfers_stop_slot()));
    ui->actionNew->setStatusTip(tr("创建一个文件"));
    ui->actionOpen->setStatusTip(tr("打开一个已经存在的文件"));
    ui->actionSave->setStatusTip(tr("保存文档到硬盘"));
    ui->actionSaveAs->setStatusTip(tr("以新的名称保存文档"));
    ui->actionExit->setStatusTip(tr("退出应用程序"));
    ui->actionUndo->setStatusTip(tr("撤销先前的操作"));
    ui->actionRedo->setStatusTip(tr("恢复先前的操作"));
    ui->actionCut->setStatusTip(tr("剪切选中的内容到剪贴板"));
    ui->actionCopy->setStatusTip(tr("复制选中的内容到剪贴板"));
    ui->actionPaste->setStatusTip(tr("粘贴剪贴板的内容到当前位置"));
    ui->actionClose->setStatusTip(tr("关闭活动窗口"));
    ui->actionCloseAll->setStatusTip(tr("关闭所有窗口"));
    ui->actionTile->setStatusTip(tr("平铺所有窗口"));
    ui->actionCascade->setStatusTip(tr("层叠所有窗口"));
    ui->actionNext->setStatusTip(tr("移动到下个编辑点"));
    ui->actionPrevious->setStatusTip(tr("移动到上个编辑点"));
    ui->actionAbout->setStatusTip(tr("显示本软件的介绍"));
    ui->actionDownload->setStatusTip(tr("将程序下载到G5控制器"));
    ui->action_Run->setStatusTip(tr("在G5运动控制器上运行程序"));
    ui->action_Simulate->setStatusTip(tr("在仿真器上对程序进行仿真"));

    //隐藏功能
    ui->actionTile->setVisible(false);
    ui->actionCascade->setVisible(false);
    ui->actionTile->setVisible(false);
//    ui->actionNext->setVisible(false);
//    ui->actionPrevious->setVisible(false);
    ui->actionCloseAll->setVisible(false);
//    ui->action_Simulate->setVisible(false);
}

//新建文件
void MainWindow::on_actionNew_triggered()
{
#if singleFile
    //新建一个文档关闭上一个文档
    if(ui->mdiArea->subWindowList().size() > 0)
        ui->mdiArea->closeAllSubWindows();
    //检查失败否关闭成功
    if(ui->mdiArea->subWindowList().size() > 0)
        return;
#endif

    ChildEdit *childEdit = createMdiChild();
    childEdit->newFile();
    childEdit->show();
    childEdit->showMaximized();

    //载入配置
    reload_setting_slot();
}

//!创建子编辑框
ChildEdit *MainWindow::createMdiChild()
{
    ChildEdit *child = new ChildEdit;
    ui->mdiArea->addSubWindow(child); //向多文档区域添加子窗口，child为中心部件
//    childedit_num = ui->mdiArea->subWindowList().size();

    //界面
    connect(child,SIGNAL(copyAvailable(bool)),ui->actionCut,
            SLOT(setEnabled(bool)));
    connect(child,SIGNAL(copyAvailable(bool)),ui->actionCopy,
            SLOT(setEnabled(bool)));

    connect(child->document(),SIGNAL(undoAvailable(bool)),
            ui->actionUndo,SLOT(setEnabled(bool)));
    connect(child->document(),SIGNAL(redoAvailable(bool)),
            ui->actionRedo,SLOT(setEnabled(bool)));
    //当子窗口关闭时通知主窗口保存路径
    connect(child,SIGNAL(sig_fileClose(QString)),
            this, SLOT(saveLastCloseFilePath_slot(QString)));

    return child;
}

//!打开文件
void MainWindow::on_actionOpen_triggered()
{
    QString lastDir = setting_config->value("ListDirs").toString();//打开上次“打开”路径
    QString fileName = QFileDialog::getOpenFileName(this,tr("打开文档"),
                                                    lastDir,
                                                    "文本文件 (*.txt);;所有文件 (*.*)"); // 获取文件路径
    qDebug()<<"filename"<<fileName;
    if (!fileName.isEmpty()) { // 如果路径不为空，则查看该文件是否已经打开
        setting_config->setValue("ListDirs", QFileInfo(fileName).path());//保存上次“打开”路径
        QMdiSubWindow *existing = findMdiChild(fileName);
        if (existing) { // 如果已经存在，则将对应的子窗口设置为活动窗口
            ui->mdiArea->setActiveSubWindow(existing);
            return;
        }

#if singleFile
    //打开一个文档关闭上一个文档
    if(ui->mdiArea->subWindowList().size() > 0)
        ui->mdiArea->closeAllSubWindows();
#endif

        ChildEdit *child = createMdiChild();
        if (child->loadFile(fileName)) {
            ui->statusBar->showMessage(tr("打开文件成功"), 2000);
            child->show();
            child->showMaximized();//子窗口最大化
            //载入配置
            reload_setting_slot();
        } else {
            child->close();
        }
    }
}

//!查找子窗口
QMdiSubWindow *MainWindow::findMdiChild(const QString &fileName)
{
    QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();

    // 利用foreach语句遍历子窗口列表，如果其文件路径和要查找的路径相同，则返回该窗口
    foreach(QMdiSubWindow *window, ui->mdiArea->subWindowList()){
        ChildEdit *mdiChild = qobject_cast<ChildEdit *>(window->widget());
        if (mdiChild->currentFile() == canonicalFilePath)
            return window;
    }
    return 0;
}

//!保存文件
void MainWindow::on_actionSave_triggered()
{
    if(activeMdiChild() && activeMdiChild()->save())
        ui->statusBar->showMessage(tr("文件保存成功"), 2000);
}

//!查看活动窗口
ChildEdit * MainWindow::activeMdiChild()
{
    // 如果有活动窗口，则将其内的中心部件转换为MdiChild类型
    if (QMdiSubWindow *activeSubWindow = ui->mdiArea->activeSubWindow())
        return qobject_cast<ChildEdit *>(activeSubWindow->widget());
    return 0;
}

//!关闭事件
void MainWindow::closeEvent(QCloseEvent *event)
{
    ui->mdiArea->closeAllSubWindows(); // 先执行多文档区域的关闭操作
    if (ui->mdiArea->currentSubWindow()) {
        event->ignore(); // 如果还有窗口没有关闭，则忽略该事件
    } else {
        writeSettings(); // 在关闭前写入窗口设置
        event->accept();
    }
}

//!写入窗口设置
void MainWindow::writeSettings()
{
    setting_config->setValue("pos", pos());   // 写入位置信息
    setting_config->setValue("size", size()); // 写入大小信息
}

//读取窗口设置
void MainWindow::readSettings()
{
    //配置检查
    if(!widget_s->checkSetting(0)){
        QMessageBox::warning(this, tr("警告"),
                                 tr("配置文件丢失或有误，请重新设置。")
                                 );
        widget_s->show();
        return;
    }
    //打开上次文档
    QString path;
    QStringList fileList = setting_config->value("LASTOPEN").value<QStringList>();
    if(fileList.isEmpty()){
        path = "";
    }else{
        path = fileList.takeFirst();
    }
    if(QFileInfo(path).isFile()){
        ChildEdit *child = createMdiChild();
        if (child->loadFile(path)) {
            ui->statusBar->showMessage(tr("打开文件成功"), 2000);
            child->show();
            child->showMaximized();//子窗口最大化
            reload_setting_slot();//重载设置
        } else {
            child->close();
        }
    }

    QSize size = setting_config->value("size", QSize(800, 600)).toSize();
    QPoint pos = setting_config->value("pos").toPoint();
    move(pos);
    resize(size);
}

// 更新菜单
void MainWindow::updateMenus()
{
    bool hasMdiChild = (activeMdiChild() != 0); // 是否有活动窗口
    ui->actionSave->setEnabled(hasMdiChild);   // 设置各个动作是否可用
    ui->actionSaveAs->setEnabled(hasMdiChild);
    ui->actionPaste->setEnabled(hasMdiChild);
    ui->actionClose->setEnabled(hasMdiChild);
    ui->actionCloseAll->setEnabled(hasMdiChild);
    ui->actionTile->setEnabled(hasMdiChild);
    ui->actionCascade->setEnabled(hasMdiChild);
    ui->actionNext->setEnabled(hasMdiChild);
    ui->actionPrevious->setEnabled(hasMdiChild);
    ui->action_Find->setEnabled(hasMdiChild);
    ui->action_Replace->setEnabled(hasMdiChild);
    ui->action_Simulate->setEnabled(hasMdiChild);
    ui->action_Option->setEnabled(!downloadPb->isVisible());
    ui->actionDownload->setEnabled(!downloadPb->isVisible() && hasMdiChild);
    ui->action_Run->setEnabled(!downloadPb->isVisible() && hasMdiChild);
    ui->action_Simulate->setEnabled(!downloadPb->isVisible() && hasMdiChild);

    actionSeparator->setVisible(hasMdiChild); // 设置间隔器是否显示

    bool hasSelection = (activeMdiChild()
                         && activeMdiChild()->textCursor().hasSelection());

    // 有活动窗口且有被选择的文本，剪切复制才可用
    ui->actionCut->setEnabled(hasSelection);
    ui->actionCopy->setEnabled(hasSelection);

    ui->actionUndo->setEnabled(activeMdiChild() // 有活动窗口且文档有撤销操作
                          && activeMdiChild()->document()->isUndoAvailable());
    ui->actionRedo->setEnabled(activeMdiChild() // 有活动窗口且文档有恢复操作
                          && activeMdiChild()->document()->isRedoAvailable());
}

void MainWindow::on_actionSaveAs_triggered()
{
    if(activeMdiChild() && activeMdiChild()->saveAs())
        ui->statusBar->showMessage(tr("文件保存成功"),2000);
}
//关闭程序
void MainWindow::on_actionExit_triggered()
{
    qApp->closeAllWindows();
}
//复制操作
void MainWindow::on_actionCopy_triggered()
{
    if(activeMdiChild()) activeMdiChild()->copy();
}
//剪切操作
void MainWindow::on_actionCut_triggered()
{
    if(activeMdiChild()) activeMdiChild()->cut();
}
//粘贴操作
void MainWindow::on_actionPaste_triggered()
{
    if(activeMdiChild()) activeMdiChild()->paste();
}
//查找窗口
void MainWindow::on_action_Find_triggered()
{
    widget_f->hide();
    widget_f->show();
}
//替换窗口
void MainWindow::on_action_Replace_triggered()
{
    widget_r->hide();
    widget_r->show();
}
//撤销操作
void MainWindow::on_actionUndo_triggered()
{
    if(activeMdiChild()) activeMdiChild()->undo();
}
//恢复菜单
void MainWindow::on_actionRedo_triggered()
{
    if(activeMdiChild()) activeMdiChild()->redo();
}
//关闭子窗口
void MainWindow::on_actionClose_triggered()
{
    ui->mdiArea->closeActiveSubWindow();
}
//关闭所有子窗口
void MainWindow::on_actionCloseAll_triggered()
{
    ui->mdiArea->closeAllSubWindows();
}

void MainWindow::on_actionTile_triggered()
{
    ui->mdiArea->tileSubWindows();
}

void MainWindow::on_actionCascade_triggered()
{
    ui->mdiArea->cascadeSubWindows();
}

void MainWindow::on_actionNext_triggered()
{
    //ui->mdiArea->activateNextSubWindow();
    activeMdiChild()->positisonMove(false);
}

void MainWindow::on_actionPrevious_triggered()
{
    //ui->mdiArea->activatePreviousSubWindow();
    activeMdiChild()->positisonMove(true);
}
//选项页面
void MainWindow::on_action_Option_triggered()
{
    widget_s->hide();
    widget_s->show();
}
//关于页面
void MainWindow::on_actionAbout_triggered()
{
    widget_ab->hide();
    widget_ab->show();
}
//打开帮助文档
void MainWindow::on_action_help_triggered()
{
    QString local_path = QString(QDir::currentPath());
    local_path.append("\\help");
    local_path.replace("/","\\");
    QProcess::startDetached("explorer " + local_path);
}
//运行模拟器
void MainWindow::on_action_Simulate_triggered()
{
    QStringList param;
    param<<activeMdiChild()->currentFile();
    QProcess::startDetached(SIMULATION, param);
}

//!文本查找功能槽
void MainWindow::showFindText_SLOT(QString exp,QTextDocument::FindFlags opt)
{
    if(!activeMdiChild()->find(exp, opt)){
        QTextCursor cursor = activeMdiChild()->textCursor();
        if(opt == QTextDocument::FindBackward)
            cursor.movePosition(QTextCursor::End);
        else{
            cursor.movePosition(QTextCursor::Start);
        }
        activeMdiChild()->setTextCursor(cursor);
        activeMdiChild()->ensureCursorVisible();
    }
}

//!文本替换功能槽
void MainWindow::showReplaceText_SLOT(QString exp, QString after, QTextDocument::FindFlags opt, int func)
{
    switch (func) {
    case 0://查找下一个
        showFindText_SLOT(exp, opt);
        break;
    case 1://替换一个
        if(activeMdiChild()->textCursor().hasSelection()){
            if(activeMdiChild()->textCursor().selectedText() == exp){
                QTextCursor textCursor = activeMdiChild()->textCursor();
                textCursor.insertText(after);
            }else{

            }
        }else{
            showFindText_SLOT(exp, opt);
        }
        break;
    case 2://替换全部
        QTextCursor setCursor = activeMdiChild()->textCursor();
        setCursor.setPosition(0);
        activeMdiChild()->setTextCursor(setCursor);
        while(activeMdiChild()->find(exp, opt)){
            if(activeMdiChild()->textCursor().selectedText() == exp){
                QTextCursor textCursor = activeMdiChild()->textCursor();
                textCursor.insertText(after);
            }
        }
        break;
    }
}
//!保存上次打开文件的路径
void MainWindow::saveLastCloseFilePath_slot(QString path)
{
    QStringList fileList = setting_config->value("LASTOPEN").value<QStringList>();
    int pos = fileList.indexOf(path);
    if(pos == -1){
        fileList.insert(0,path);
    }else{
        fileList.move(pos,0);
    }
    fileList = fileList.mid(0,LASTOPENFILENUM);
    setting_config->setValue("LASTOPEN", fileList);
    emit sig_savelastfile(fileList);
}
//!重载设置槽
void MainWindow::reload_setting_slot()
{
    QFont getfont;
    getfont.setPointSize(setting_config->value("FontSize").toInt());
    getfont.setFamily(setting_config->value("Font").toString());

    for(int i = 0; i < ui->mdiArea->subWindowList().size(); i++){
        ChildEdit * child = qobject_cast<ChildEdit *>(ui->mdiArea->subWindowList().at(i)->widget());
        child->setFont(getfont);//字体;
        child->setTabStopWidth(7.5 * setting_config->value("TabSize").toInt());//tab缩进
        child->setupHighLightTool(setting_config->value("HighLighter").toBool());//打开高亮
        qDebug()<<"reload Setting";
    }
}
//!打开文件槽
void MainWindow::FileOpen_slot(QString url)
{
//    qDebug()<<"mainwindow FileOpen_slot:"<<url;
    QString path = url;
#if singleFile
    //打开一个文档关闭上一个文档
    if(ui->mdiArea->subWindowList().size() > 0)
        ui->mdiArea->closeAllSubWindows();
#endif
    if(QFileInfo(path).isFile()){
        ChildEdit *child = createMdiChild();
        if (child->loadFile(path)) {
            ui->statusBar->showMessage(tr("打开文件成功"), 2000);
            child->show();
            child->showMaximized();//子窗口最大化
            reload_setting_slot();//重载设置
        } else {
            child->close();
        }
    }
}
//!转到行槽
void MainWindow::on_action_goto_triggered()
{
    int lineNum= QInputDialog::getInt(this, tr("转到行"),
                          QString("%1(0-%2)").arg(tr("请输入行号"))
                                      .arg(activeMdiChild()->blockCount()));
    activeMdiChild()->gotoLine(lineNum);
}

//传送终止处理槽
void MainWindow::transfers_stop_slot(int value)
{
    QString tittle,content;
    switch(value){
    case 0:
        tittle = tr("提示");
        content = tr("下载完成");
        break;
    case -1:
        tittle = tr("警告");
        content = tr("连接超时，请检查设置与连接！");
        break;
    case -2:
        tittle = tr("警告");
        content = tr("控制器中止连接，请检查控制器设置！");
        break;
    case -3:
        tittle = tr("警告");
        content = tr("串口无法打开，请检查设置与连接！");
        break;
    default:
        return;
    }
    fileTranferFlag = false;
    QMessageBox::warning(this, tittle, content);
}
//取消传输
void MainWindow::transfers_stop_slot()
{
    QString tittle,content;
    tittle = tr("警告");
    content = tr("下载已取消！");
    userUart.close();
    senddata.clear();
    downloadPb->setVisible(false);
    cancelButton->setVisible(false);
    fileTranferFlag = false;
    QMessageBox::warning(this, tittle, content);
}
//程序下载
void MainWindow::on_actionDownload_triggered()
{
    if(!activeMdiChild()){
        QMessageBox::warning(this, tr("警告"),
                             tr("未打开文档，下载失败!")
                             );
        return;
    }
    QString cdata;
    cdata.clear();
    cdata = activeMdiChild()->toPlainText();

#if G5
    QList<QByteArray> datalist;
    int addr = setting_config->value("DevAddr").toInt();
    int pakLen = setting_config->value("PakLen").toInt();
    datalist = ordermaker.data_subpackage(cdata, pakLen);//处理包
    //加入文件名
    senddata<<ordermaker.make_codeDownload_order(addr, FILENAME,
                                                 activeMdiChild()->getCurrentFileFromInfo().toLocal8Bit());
    //加入内容
    for(int i = 0; i < datalist.size(); i++)
        senddata<<ordermaker.make_codeDownload_order(addr, FILEDATA, datalist.at(i));

    senddata<<ordermaker.make_endpackage(0x0);//加入发送完毕包

#elif K3
    QStringList jcodelist = cdata.split("\n", QString::SkipEmptyParts);

    for(int j = 0; jcodelist.size() > 0; j++){
        QStringList sendList;
        sendList.clear();
        for(int i = 0; i < 2; i++){
            if(jcodelist.size() > 0)
                sendList << jcodelist.takeFirst();
        }
        QString rawString = json_handle.order_jcodeString("1.txt", sendList);
        QByteArray gbkstring = rawString.toLocal8Bit();//gbk
        QString sendjson = json_handle.order_makeup(json_handle.order_jcodeCrcexplain(gbkstring),
                                                    0,
                                                    rawString);
        senddata << sendjson.toLocal8Bit();
    }
    senddata << json_handle.order_makeup(json_handle.order_jcodeCrcexplain(
                        json_handle.order_runningstatus()), 0, json_handle.order_runningstatus())
                        .toLocal8Bit();
    qDebug()<<senddata;
#endif
    fileTranferFlag = true;
    if(userUart.open() < 0){
        emit sig_transfers_stop(UNLINK);
        return;
    }
    sendtimer.start(200);

    //界面控制
    ui->statusBar->clearMessage();
    downloadPb->setRange(0, senddata.size());
    downloadPb->setVisible(true);
    cancelButton->setVisible(true);
    widget_f->close();
    widget_r->close();
}

//数据接收槽
void MainWindow::uartgetdata_slot(int ret)
{
    if(ret < 0){
        qDebug()<<"timerout"<<ret;
        userUart.close();
        senddata.clear();
        if(fileTranferFlag)
            emit sig_transfers_stop(OVERTIME);
    }else{
        //接收成功处理
        //qDebug()<<userUart.uart_getString();
        //检查返回命令
#if G5
        int check = ordermaker.check_returnOrder(userUart.uart_getString());
#elif K3
        int check;
        QString str(userUart.uart_getString());
        if(json_explain.explainReply(json_handle.order_replyexplain(str).value("dataString"))){
            check = 0;
        }else{
            if(senddata.size()<=1)//是否为最后一包
                check = 0;
            else
                check = -1;
        }
#endif
        switch(check){
        case 0://正常
            if(senddata.isEmpty() && fileTranferFlag)
                emit sig_transfers_stop(COMPLETE);
            break;
        case -1://重发
            userUart.send(sendbuf);
            return;
            break;
        case -2://传送终止
            userUart.close();
            senddata.clear();
            if(fileTranferFlag)
                emit sig_transfers_stop(ABORT);
            break;
        }
    }
    sendtimer.start();
}

//数据发送槽
void MainWindow::uartsentdata_slot()
{
    sendbuf = senddata.dequeue();
    userUart.send(sendbuf);
    emit sig_processChange(downloadPb->maximum() - senddata.size());
}

//发送队列数据检查槽
void MainWindow::checkQueueData_slot()
{
    if(senddata.isEmpty()){//检查队列是否有数据
        userUart.close();
        sendtimer.stop();
        downloadPb->setVisible(false);
        cancelButton->setVisible(false);
    }else{
        emit sig_readytosent();
        sendtimer.stop();
    }
}

//点击运行按钮
void MainWindow::on_action_Run_triggered()
{
    if(!senddata.isEmpty())
        return;
    int addr = setting_config->value("DevAddr").toInt();
    QByteArray data;
    data.resize(1);
    data[0] = 0x0;
    senddata<<ordermaker.make_codeDownload_order(addr, RUNONLINE, data);
    userUart.open();
    sendtimer.start(200);
}
